import React, {PropsWithChildren, useCallback, useEffect, useRef, useState} from 'react'
import {
    clearItemsByYearAndMonth,
    createMarketSaleDocument,
    downloadImportTemplate,
    importMarketSaleDocumentItems, importMarketSaleDocumentItemsByMonth,
    MarketSaleDocumentDetail,
    MarketSaleDocumentItem, moveItemsToAnotherDocument, submitMarketSaleDocument, validateMarketSaleDocument
} from "../apis/MarketSaleDocumentApi";
import {Button, Col, Descriptions, Popover, Row, Space, Typography, Upload} from "antd";
import {convertAntdTableToExcelWithOptions, ExportedColumnProps} from "../utils/AntdTableUtils";
import useMessage from "antd/es/message/useMessage";
import {OffsetDateTime} from "@js-joda/core";
import {DATE_WITH_TIME_FORMATER} from "../utils/Date";
import TableColumnSelectModal from "./TableColumnSelectModal";
import ArrayUtils from "@zxy-cn/array-utils";
import LoadableButton from "./LoadableButton";
import {ErrorResponse} from "@zxy-cn/fetcher";
import {QuestionCircleOutlined, UploadOutlined} from "@ant-design/icons";
import {saveTo, saveWorkbookTo} from "../utils/FileSaver";
import employeeAuthorizationStore from "../store/EmployeeAuthorizationStore";
import DataPageLayout from "./DataPageLayout";
import GoodsTable from "./GoodsTable";
import SingleSelectPopover from "./SingleSelectPopover";
import {MarketAccountResponse} from "../apis/MarketAccountApi";
import {it} from "node:test";
import ConfirmPopover from "./ConfirmPopover";

export interface MarketAccountMonthDocumentDetailPageProps extends PropsWithChildren {
    marketId: number
    month: number
    year: number
    accountId: number
    data?: MarketSaleDocumentDetail
    onQuery: () => Promise<void>
    onChange: (data: MarketSaleDocumentDetail) => void
    accounts: MarketAccountResponse[]
    onMove: (goodsIds: number[], targetAccount: number) => Promise<void>
}

const MarketAccountMonthDocumentDetailPage: React.FC<MarketAccountMonthDocumentDetailPageProps> = (props) => {
    const {marketId, data, year, month} = props
    const [loading, setLoading] = useState(false)
    const doQuery = useCallback(() => {
        setLoading(true)
        props.onQuery().finally(() => {
            setLoading(false)
        })
    }, [props.onQuery]);
    useEffect(() => {
        doQuery()
    }, [marketId, year, month]);

    let columnsRef = useRef<ExportedColumnProps<MarketSaleDocumentItem>[]>();
    const [importing, setImporting] = useState(false)
    let [messageApi, messageHolder] = useMessage();
    const [openExportColumnSelectModal, setOpenExportColumnSelectModal] = useState(false)

    const [selectedItemIds, setSelectedItemIds] = useState<number[]>([])

    const [moveToTargetAccountId, setMoveToTargetAccountId] = useState<number>()

    const [showConfirmClearPopover, setShowConfirmClearPopover] = useState(false)
    return (
        <>
            {messageHolder}
            {!loading && !!data ? <Descriptions title={"销售明细"}>
                <Descriptions.Item label={"卖场"}>{data?.market?.name}</Descriptions.Item>
                <Descriptions.Item
                    label={"单品数量"}>{data.items.length}</Descriptions.Item>
                <Descriptions.Item
                    label={"金额合计"}>{ArrayUtils.sum(data?.items ?? [], item => item.totalFee).toFixed(2)}</Descriptions.Item>
                <Descriptions.Item label={"创建人"}>{data?.createdBy?.name}</Descriptions.Item>
                {!!data?.createdDateTime && <Descriptions.Item
                    label={"创建时间"}>{data?.createdDateTime.format(DATE_WITH_TIME_FORMATER)}</Descriptions.Item>}
                {!!data?.auditedDateTime ? <Descriptions.Item
                    label={"审核时间"}>{data.auditedDateTime.format(DATE_WITH_TIME_FORMATER)}</Descriptions.Item> : undefined}
                {!!data?.note ? <Descriptions.Item
                    label={"备注"}>{data.note}</Descriptions.Item> : undefined}
            </Descriptions> : null}


            {/*{((employeeAuthorizationStore.hasAuthority("卖场_销售单_开单") && !data?.submittedDateTime) || (employeeAuthorizationStore.hasAuthority("卖场_销售单_修改") && !data?.auditedDateTime)) &&*/}
            {/*    !!data &&*/}
            {/*    <EditOrderItemRow<AddMarketSaleDocumentItemRequest, GoodsWithMarketInStore>*/}
            {/*        request={{editMarketSaleDocumentId: id}}*/}
            {/*        fetchGoods={() =>*/}
            {/*            getAllGoodsWithMarketInStoreInMakret(data.market.id).then(res => {*/}
            {/*                return res.data*/}
            {/*            })}*/}
            {/*        optionRender={it => <div style={{display: 'flex', flexDirection: "column"}}>*/}
            {/*            <div style={{display: "flex", justifyContent: 'space-between'}}>*/}
            {/*                <span>{it.barcode}</span><span>{it.name}</span>*/}
            {/*            </div>*/}
            {/*            <Space size={24}><span>卖场存货:{it.amountInMarket ?? "无"}</span><span>库存:{it.amount}</span></Space>*/}
            {/*        </div>}*/}
            {/*        onFinish={async (values) => {*/}
            {/*            return addMarketSaleDocumentItem(id, values).then(() => {*/}
            {/*                query()*/}
            {/*            })*/}
            {/*        }} existedGoodsIds={data?.items?.map(it => it.id) ?? []}/>}*/}
            <DataPageLayout leftActions={<>
                <TableColumnSelectModal
                    availableColumns={["卖场","户头","名称", "条码", "数量", "金额小计",  "品牌", "类别", "厂商", "库存", "零售价", "箱规"]}
                    open={openExportColumnSelectModal} onConfirm={async fields => {
                    let columns = Array.from(columnsRef.current!!);
                    ArrayUtils.insertBefore(columns, value => value.title === "条码", {
                        title: "卖场",
                        key: "market.name",
                        generateExcelValue: (_, value: MarketSaleDocumentItem) => {
                            return data?.market.name??""
                        },
                    })
                    ArrayUtils.insertBefore(columns, value => value.title === "条码", {
                        title: "户头",
                        key: "account.name",
                        generateExcelValue: (_, value: MarketSaleDocumentItem) => {
                            return data?.account.name
                        },
                    })
                    let workbook = await convertAntdTableToExcelWithOptions(columns, data?.items ?? [], {
                        selectedColumns: fields, postHandler: (workshet, data) => {
                            let lastRowNumber = workshet.rowCount;
                            // let priceDifferenceIndex = columns.findIndex(it => it.key === priceDifference);
                            // if (priceDifferenceIndex != -1) {
                            //     let cell = workshet.getCell(lastRowNumber + 1, priceDifferenceIndex + 1);
                            //     cell.value = "特价合计：" + ArrayUtils.sum(data, item => (item.totalFee / item.amountInOrder - item.price) < -item.price * 0.1 ? item.totalFee : 0).toFixed(2)
                            // }
                            //
                            const feeSumIndex = columns.findIndex(it => it.dataIndex === "totalFee");
                            if (feeSumIndex != -1) {
                                let cell = workshet.getCell(lastRowNumber + 1, feeSumIndex + 1);
                                cell.value = +ArrayUtils.sum(data, item => item.totalFee).toFixed(2)
                            }
                        }
                    },);
                    await saveWorkbookTo(workbook, `${data?.market?.name}${data?.account?.name}${year}年${month}月销售记录`)
                    setOpenExportColumnSelectModal(false)
                }} cacheKey={"marketSaleDocument"} onCancel={_ => setOpenExportColumnSelectModal(false)}/>
                <LoadableButton onClick={async (_) => {
                    setOpenExportColumnSelectModal(true)
                }}>
                    导出
                </LoadableButton>


                <Row>
                    <Upload fileList={[]}
                            accept={"application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}
                            maxCount={1}
                            beforeUpload={file => {
                                if (!data) {
                                    createMarketSaleDocument(props.accountId, {
                                        year: props.year,
                                        month: props.month,
                                    }).then(() => {
                                        doQuery()
                                        doUpload()
                                    })
                                } else {
                                    doUpload()
                                }

                                function doUpload() {
                                    setImporting(true)
                                    importMarketSaleDocumentItemsByMonth(props.accountId, year, month, file).then(response => {
                                        doQuery()
                                    }).catch((response: ErrorResponse) => {
                                        if (typeof response === "object") {
                                            messageApi.error(JSON.stringify(response.data))
                                        }
                                    }).finally(() => {
                                        setImporting(false)
                                    });
                                }

                                return false
                            }}>
                        <Button icon={<UploadOutlined/>} loading={importing}>导入</Button>
                    </Upload>
                    <Popover title={"导入货品"} content={
                        <Typography>
                            <Typography.Paragraph>
                                按照约定的格式上传excel文件。
                                <Typography.Link onClick={() => {
                                    downloadImportTemplate().then(res => res.data)
                                        .then(blob => {
                                            saveTo(blob, "导入销售数据模板.xlsx")
                                        })

                                }}>下载模板</Typography.Link>
                            </Typography.Paragraph>
                            <Typography.Paragraph>
                                <ul>
                                    <li>只能导入已有资料的商品</li>
                                    <li>条码不可重复（同一个表格中多个相同的条码会被合并）</li>
                                    <li>已存在的商品会被忽略</li>
                                    <li>仅使用文件的第一个Sheet</li>
                                </ul>
                            </Typography.Paragraph>
                        </Typography>
                    }><QuestionCircleOutlined/></Popover></Row>
                {employeeAuthorizationStore.hasAuthority("卖场_销售单_审核")
                && !data?.auditedDateTime
                && !!data?.submittedDateTime ?
                    <LoadableButton onClick={async () => {
                        await validateMarketSaleDocument(data?.id)
                        props.onChange({...data!, auditedDateTime: OffsetDateTime.now()})
                    }}>验收</LoadableButton>
                    : undefined}

                {
                    <LoadableButton onClick={async (_) => {
                        // await submitMarketSaleDocument(id)
                        // setData({...data!, submitDateTime: OffsetDateTime.now()})
                    }}>
                        打印
                    </LoadableButton>}
            </>} rightActions={<>
                {employeeAuthorizationStore.hasAuthority("卖场_销售单_修改") && !data?.submittedDateTime &&
                    <>{!!data &&
                        <SingleSelectPopover<number> title={"批量移动"}
                                                     key={selectedItemIds.length}
                                                     initialValue={moveToTargetAccountId}
                                                     options={props.accounts.filter(it => it.id !== data.account.id).map(it => ({
                                                         label: it.name,
                                                         value: it.id,
                                                     }))} required placeholder={"选择户头"}
                                                     onConfirm={async value => {
                                                         setMoveToTargetAccountId(value)
                                                         let goodsIds = selectedItemIds;

                                                         await props.onMove(goodsIds, value!!)
                                                         setSelectedItemIds([])
                                                     }}><Button disabled={!selectedItemIds.length}>
                            批量移动{selectedItemIds.length ? `(${selectedItemIds.length})` : ""}
                        </Button></SingleSelectPopover>}</>

                }
                {employeeAuthorizationStore.hasAuthority("卖场_销售单_修改") && !data?.submittedDateTime && <>
                    <ConfirmPopover description={"是否要清空此销售单"} onConfirm={async ()=>{
                        await clearItemsByYearAndMonth(props.accountId, year, month,)
                        setSelectedItemIds([])
                        props.onChange({
                            ...data!,
                            items:[],
                        })
                    }} open={showConfirmClearPopover} onOpenChange={setShowConfirmClearPopover}>
                        <Button>清空</Button>
                    </ConfirmPopover>
                </>}
                {employeeAuthorizationStore.hasAuthority("卖场_销售单_开单") && !data?.submittedDateTime &&
                    <>{!!data && <LoadableButton onClick={async (event) => {
                        await submitMarketSaleDocument(data?.id)
                        props.onChange({...data!, submittedDateTime: OffsetDateTime.now()})
                    }}>
                        提交
                    </LoadableButton>}</>

                }
            </>}>

                <GoodsTable<MarketSaleDocumentItem> loading={loading}
                                                    rowSelection={{
                                                        type: "checkbox",
                                                        fixed: true,
                                                        selectedRowKeys: selectedItemIds,
                                                        onChange: (keys => {
                                                            setSelectedItemIds(keys as number[])
                                                        })
                                                    }}
                                                    pagination={false}
                                                    size={"small"}
                                                    scroll={{
                                                        y: 800,
                                                        scrollToFirstRowOnChange: true,

                                                    }}
                                                    virtual
                                                    customColumns={columns => {
                                                        ArrayUtils.insertAfter(columns, value => value.dataIndex === "name", {
                                                            dataIndex: "amountInOrder",
                                                            title: "数量",
                                                            fixed: "left",
                                                        },)
                                                        ArrayUtils.insertAfter(columns, value => value.dataIndex === "amountInOrder", {
                                                            dataIndex: "totalFee",
                                                            title: "金额小计",
                                                            fixed: "left",
                                                        },)
                                                        let priceColumn = columns.find(it => it.dataIndex === "price");
                                                        ArrayUtils.remove(columns, priceColumn)
                                                        ArrayUtils.insertAfter(columns, value => value?.dataIndex === "totalFee", {
                                                            ...priceColumn,
                                                            fixed: "left",
                                                        },)
                                                        ArrayUtils.insertAfter(columns, value => value.dataIndex === "price", {
                                                            dataIndex: "diff",
                                                            title: "零售价差额",
                                                            fixed: "left",
                                                            render: (_, record, __) => {
                                                                let diff = Number((record.totalFee / record.amountInOrder - record.price).toFixed(2))
                                                                const per = `(${Math.abs(diff/record.price*100).toFixed(0)}%)`;
                                                                if (diff > 0) {
                                                                    return `+${diff}${per}`
                                                                } else if (diff < 0) {
                                                                    return `${diff}${per}`
                                                                } else {
                                                                    return 0
                                                                }
                                                            }
                                                        },)
                                                        columnsRef.current = columns;
                                                        return columns;
                                                    }}
                                                    rowKey={"id"} data={data?.items ?? []}>
                </GoodsTable>
            </DataPageLayout>

        </>
    )
}

export default MarketAccountMonthDocumentDetailPage


